<template>
  <div class="registered">
    <div class="nav">
      <van-nav-bar left-arrow border @click-left="onClickLeft">
        <template #title>
          <span class="title-bar">注册</span>
        </template>
      </van-nav-bar>
    </div>
    <div class="registered-form">
      <div class="form-top"></div>
      <van-form @submit="onSubmit" validate-trigger='onSubmit'>
        <van-field
          v-model="email"
          name="email"
          label="邮箱"
          clearable
          :maxlength='20'
           @blur="verificationEmail"
          :error-message='emailerror'
           placeholder="请输入邮箱"
          :rules="[{ pattern, message: '请输入正确的邮箱' }]"
        />
        <van-field
          v-model="random"
          center
          clearable
          name="random"
          label="邮箱验证码"
          :maxlength='6'
          type='number'
          placeholder="请输入邮箱验证码"
          :rules="[{ required: true}]"
        >
          <template #button>
            <van-button size="small" type="primary" class="sendcode" @click="getEmailCode" v-if="!ing">
              发送邮箱验证码
            </van-button>
             <span v-else class="Counter">
                {{ countDown | Digitalcomplement }}
             </span>
          </template>
        </van-field>
        <van-field
          v-model="loginName"
          type="loginName"
          name="loginName"
          clearable
          label="用户名"
          :maxlength='10'
           placeholder="用户名为6位以上数字字母组合"
          :rules="[{ pattern:userNameTest , message:'用户名格式不符合要求'}]"
        />
        <van-field
          v-model="passWord"
          type="passWord"
          name="passWord"
          clearable
          label="密码"
          :maxlength='16'
          placeholder="设置密码6-12位"
          :rules="[{  pattern:passwordTest , message:'设置新密码6-12位字符' }]"
        />
        <div  style="margin: 16px">
          <van-button round block type="info" native-type="submit">注册</van-button>
        </div>
        <div class="agreement">
          <van-checkbox v-model="Isagreement" icon-size="18px"> <span>点击注册，那代表你同意用户隐私协议</span></van-checkbox>
        </div>
      </van-form>
    </div>
  </div>
</template>


<script>
import { Createanaccount ,Getverificationcode , EffectivenessEmail} from '../../api/login'
import { Toast } from 'vant';

import { reactive, toRefs ,onBeforeUnmount} from "@vue/composition-api";

export default {
  name: "registered",
  // eslint-disable-next-line no-unused-vars
  setup (props,{ root }) {
    
      const state = reactive({
            email: "",
            random: "",
            passWord:"",
            loginName:"",
            // 邮箱正则表达式
            pattern: /^[a-zA-Z0-9_-]+@[a-zA-Z0-9_-]+(\.[a-zA-Z0-9_-]+)+$/,
            time:null,
            countDown:0,
            ing:false,
            Isagreement:'',
            passwordTest: /^.{6,12}$/,
            userNameTest:/^\w{6,}$/,
            emailerror:""
      })
      const onClickLeft =()=>{ root.$router.go(-1)}

      // 提交注册 
      const onSubmit = async (params)=>{
        if(state.Isagreement){
          params.random = Number(params.random);
            try {
                let res = await Createanaccount(params);
                if(res.success === false){
                  Toast.fail(res.msg);
                }else{
                  Toast.success('注册成功,你可以用此账号进行登录');
                  root.$router.push({ name: 'login'})
                }
            } catch (error) {
              console.log(error);
            }
        }else{
          Toast.success('请先阅读同意用户隐私协议');
        }
      }
      // 获得验证码
      async function getEmailCode(e){
        e.preventDefault()
        if(state.pattern.test(state.email)){
          state.countDown = 0
          state.ing = true
          state.time =  setInterval(() => {
            state.countDown++
            if(state.countDown === 60){
              clearInterval(state.time)
              state.ing = false
            }
          }, 1000);
          let res = await Getverificationcode(state.email)
          if(res.msg === '操作成功'){
          Toast.success('验证码发送成功');
          }
        }else{
          Toast.fail('请输入正确的邮箱');
        }
     }

      // 验证邮箱是否注册
      async function verificationEmail(e){
        console.log(e);
        const email = e.target.value
        if(state.pattern.test(email)){
          let res = await EffectivenessEmail({ email })
          if(!res.success){
            state.emailerror = '此邮箱已注册，无法再次注册'
          }
        }
      }
      // 清除副作用
      onBeforeUnmount(()=>{
          clearInterval(state.time)
          state.ing = false
      })

      return{
        ...toRefs(state),
        onClickLeft,
        onSubmit,
        getEmailCode,
        verificationEmail
      }
  },
  filters:{
    Digitalcomplement(val){
      if(val <= 10){
        return  "0" + val 
      }else{
        return val
      }
    }
  }
};
</script>

<style lang="less" scoped>
@import url("../../commonStyles/size.less");

.rem(@name,@px){
  @name: @px / 75
}

.registered {
  margin: 0;
  padding: 0;
}
.form-top{
  height: 250rem / 75;
}

.sendcode{
 background-color: 75;
 border: none;
}
.Counter{
  font-size: @Size30;
  color: @primary;
  margin-right: @Size20;
}
.agreement{
   padding: 0  0.38rem;
   font-size: @Size27;
  span{
     color: #999;
  }
}
</style>